/* eslint-disable no-unused-vars */
const path = require('path')
const { getFileEntries } = require('./utils/build')
const { WebpackManifestPlugin } = require('webpack-manifest-plugin')
const resolve = dir => path.join(__dirname, dir)
const {
  PUBLIC_PATH,
  PROXY_TARGET,
  DEV_PORT,
  API_ROOT,
  OUTPUT_DIR,
  MANIFEST_FILE_NAME
} = process.env
const isProduction = process.env.NODE_ENV === 'production'
module.exports = {
  runtimeCompiler: true,
  // filenameHashing: false,
  publicPath: PUBLIC_PATH,
  outputDir: OUTPUT_DIR,
  configureWebpack: {
    resolve: {
      alias: {
        '@': resolve('src'),
        '@comps': resolve('src/components')
      }
    },
    plugins: [
      new WebpackManifestPlugin({
        fileName: MANIFEST_FILE_NAME,
        serialize: manifest => {
          return `window.manifest=${JSON.stringify(manifest, null, 2)}`
        }
      })
      // new Webpack.HotModuleReplacementPlugin()
    ]
  },
  pages: extendPages(
    {
      'admin.course': {
        // page 的入口
        entry: 'src/entry/course/index.js',
        // 模板来源
        template: 'src/entry/course/index.html',
        // 在 dist/index.html 的输出
        filename: 'course/index.html',
        // 在这个页面中包含的块，默认情况下会包含
        // 提取出来的通用 chunk 和 vendor chunk。
        chunks: [
          'admin.course'
        ]
      }
    },
    isProduction
  ),
  lintOnSave: isProduction,
  devServer: {
    port: parseInt(DEV_PORT, 10) || 9000,
    historyApiFallback: false,
    proxy: {
      ['^' + API_ROOT]: {
        target: PROXY_TARGET,
        ws: true,
        changeOrigin: true
      }
    }
  },
  chainWebpack(config) {
    config.module.rule('svg').exclude.add(resolve('./src/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
    config.when(isProduction, config => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [{ inline: /runtime\.*\.js$/ }])
        .end()
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          elementUI: {
            name: 'chunk-elementUI', // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })
    })
  }
}

function extendPages(configs, ignoreEntryWithJsFile) {
  for (const conf in configs) { // 提取出来的通用 chunk 和 vendor chunk。
    if (!isProduction) {
      configs[conf] && configs[conf].chunks && configs[conf].chunks.unshift('chunk-common')
      configs[conf] && configs[conf].chunks && configs[conf].chunks.unshift('chunk-vendors')
    } else {
      configs[conf] && configs[conf].chunks && configs[conf].chunks.unshift('chunk-commons')
      configs[conf] && configs[conf].chunks && configs[conf].chunks.unshift('chunk-elementUI')
      configs[conf] && configs[conf].chunks && configs[conf].chunks.unshift('chunk-libs')
    }
  }

  const [, baseConfig] = Object.entries(configs)[0]
  const fileEntries = getFileEntries(path.join(__dirname, './src/entry'))
  for (const [key, config] of Object.entries(fileEntries)) {
    // filter
    if (!config.template) {
      // 跳过
    } else if (configs[key]) {
      // configs优先
    } else {
      // copy to configs
      config.filename = key.split('.').join('/') + '.html'
      if (config.entry) {
        if (!isProduction) {
          config.chunks = ['chunk-vendors', 'chunk-common', key]
        } else {
          config.chunks = [
            'chunk-libs',
            'chunk-elementUI',
            'chunk-commons', key]
        }
      } else if (ignoreEntryWithJsFile) {
        // 忽略 无对应 .js 文件的entry
        continue
      }
      configs[key] = Object.assign({}, baseConfig, config)
    }
  }
  return configs
}
